Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Tuples

Modify tuples

In Python, tuples are immutable. This means that once a tuple is created, you cannot change its content. However, there are some indirect ways to modify the contents of a tuple.

1. Concatenation

You can concatenate or join two tuples to create a new one. This doesn’t change the original tuples but creates a new one.
Concatenate two tuples using (+) operator tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) new_tuple = tuple1 + tuple2 print(new_tuple)

Output

(1, 2, 3, 4, 5, 6)

2. Assign values directly

In a tuple, we can assign or change values directly after changing to list using index
Assign values to tuple using index tuple1 = (1, 2, 3, 4) tuple1=list(tuple1) tuple1[3] = 5 tuple1=tuple(tuple1) print(tuple1)

Output

(1, 2, 3, 5)

3. Repetition

You can repeat the elements in a tuple a specified number of times to create a new tuple.
How to repeat elements in a tuple in python tuple1 = (1, 2, 3) new_tuple = tuple1 * 3 print(new_tuple)

Output

(1, 2, 3, 1, 2, 3, 1, 2, 3)

4. Conversion to List

Since tuples are immutable, one common practice is to convert a tuple into a list, modify the list, and then convert the list back into a tuple.
Converting tuple to list and list to tuple in python tuple1 = (1, 2, 3) list1 = list(tuple1) list1.append(4) # Modify the list tuple1 = tuple(list1) print(tuple1)

Output

(1, 2, 3, 4)

5. Nested Tuples

If a tuple contains mutable elements like lists, those elements can be changed.
Nested tuple example in python tuple1 = (1, 2, [3, 4]) tuple1[2][0] = 5 print(tuple1)

Output

(1, 2, [5, 4])

Remember, while these methods allow you to produce the effect of modifying a tuple, they do not actually modify the original tuple. Instead, they create new tuples or modify mutable elements within the tuple. The immutability of tuples is a feature of Python that helps ensure the integrity of data. It’s important to choose the right data structure for your needs in your Python programs. If you need a collection of data that can change, consider using a list or a dictionary. If you need a collection of data that should not change, consider using a tuple."

  📌TAGS

★python ★ tuple ★ methods

Tutorials